﻿using System;
using System.Collections.Generic;
using HMIS.FrameWork.DomainBase;
using HMIS.FrameWork.Repository;
using HMIS.FrameWork.Repository.Nhb;
using HMIS.Infrastructure.Core.Authority;

namespace HMIS.Infrastructure.Core.Repositories.Impl
{
	public class HospUserRepositoryImpl : RepositoryNhbImpl<HospUser>, IHospUserRepository
	{
		#region IHospUserRepository 成员

		/// <summary>
		/// 查询用户基本信息
		/// </summary>
		/// <param name="start"></param>
		/// <param name="limit"></param>
		/// <param name="sort"></param>
		/// <param name="dir"></param>
		/// <param name="filters"></param>
		/// <param name="total"></param>
		/// <returns></returns>
		public IList<HospUser> GetPlist(int start, int limit, string sort, string dir, List<DataFilter> filters, out long total)
		{
			// 排序
			string ordStr = string.IsNullOrEmpty(sort) ? string.Empty : "order by t." + sort + " " + dir;
			// 筛选
			string strFilter = base.GetHqlstrByExtFilter(filters, "t");//通过刚才基类的方法把filters转换成HQL字符串
			// sqlWhere
			string strSqlWhe = @" from HospUser as t left join fetch t.Department "
				+ (string.IsNullOrEmpty(strFilter) ? string.Empty : " where " + strFilter);
			// 查询
			var q = Session.CreateQuery(@"select t " + strSqlWhe + ordStr);
			// 分页
			if (limit > 0)
				q.SetFirstResult(start).SetMaxResults(limit);

			total = Session.CreateQuery(@"select count(*) " + strSqlWhe.Replace(" join fetch ", " join ")).UniqueResult<long>();
			return q.List<HospUser>();
		}
		
		public IList<HospUser> GetPlistAll(int start, int limit, string sort, string dir, List<DataFilter> filters, out long total)
		{
			var strFilter = base.GetHqlstrByExtFilter(filters, "u");
			sort = "u." + sort;

			strFilter = strFilter.Replace("u.Departments", "d");
			strFilter = strFilter.Replace("u.Roles", "r");

			var query = Session.CreateQuery(@"select distinct u from HospUser as u
												left join u.Departments as d
												left join u.Roles as r"
					+ (string.IsNullOrEmpty(strFilter) ? string.Empty : " where " + strFilter)
					+ " order by " + sort + " " + dir)
					.SetFirstResult(start)
					.SetMaxResults(limit);

			total = Session.CreateQuery(@"select count(distinct u) from HospUser as u
											left join u.Departments as d
											left join u.Roles as r"
				 + (string.IsNullOrEmpty(strFilter) ? string.Empty : " where " + strFilter))
				.UniqueResult<long>();

			return query.List<HospUser>();
		}

		public IList<HospUser> QueryPList(string query, int start, int limit, string sort, string dir, List<DataFilter> filters, out long total)
		{
			// filter
			var strFilter = base.GetHqlstrByExtFilter(filters, "t");
			// 排序
			string ordStr = string.IsNullOrEmpty(sort) ? string.Empty : " order by t." + sort + " " + dir;
			// sql条件
			string sqlStr = @"from HospUser as t 
								where (lower(t.Code) like lower(:query)
									or lower(t.InputCode1) like lower(:query) 
									or lower(t.InputCode2) like lower(:query) 
									or lower(t.InputCode3) like lower(:query))"
				+ (string.IsNullOrEmpty(strFilter) ? string.Empty : " and " + strFilter);


			var q = Session.CreateQuery(@"select t " + sqlStr + ordStr)
						.SetString("query", "%" + query + "%");
			if (limit > 0)
				q.SetFirstResult(start).SetMaxResults(limit);

			total = Session.CreateQuery(@"select count(*) " + sqlStr)
				.SetString("query", "%" + query + "%")
				.UniqueResult<long>();

			return q.List<HospUser>();
		}

		public bool IsFieldExist(string fieldName, string fieldValue, string id)
		{
			return base.IsFieldExist(fieldName, fieldValue, id, null);
		}

		public IList<HospUser> GetListByRoleCode(string roleCode, string sort, string dir)
		{
			string ordStr = string.IsNullOrEmpty(sort) ? string.Empty : " order by t." + sort + " " + dir;
			var query = Session.CreateQuery(@"select distinct t from HospUser as t
												left join t.Roles as r
											   where t.State = :PersonState and r.IsDelete = 0 and r.Code = :RoleCode"
				   + ordStr)
				   .SetString("RoleCode", roleCode)
				   .SetEnum("PersonState", PersonState.Normal);

			return query.List<HospUser>();
		}

		public IList<object[]> GetUserListByDep(string query, string depCode, int start, int limit, string sort, string dir, List<DataFilter> filters, out long total)
		{
			// filter
			var strFilter = base.GetHqlstrByExtFilter(filters, "t");
			// 排序
			string ordStr = string.IsNullOrEmpty(sort) ? string.Empty : " order by t." + sort + " " + dir;
			// sql条件
			string sqlStr = @" from HospUser as t 
								left join fetch t.UserRoleDep r
								where t.State = :PersonState 
									and t.InputCode1 like (:query)
									and r.IsDelete = 0 
									and t.Departments.Code = :DepCode"
				+ (string.IsNullOrEmpty(strFilter) ? string.Empty : " and " + strFilter);

			var q = Session.CreateQuery(@"select t.Id, t.LoginName, t.Name, r.Id, r.Code, r.Name " + sqlStr + ordStr)
				.SetString("query", query + "%")
				.SetString("DepCode", depCode)
				.SetEnum("PersonState", PersonState.Normal);
			if (limit > 0)
				q.SetFirstResult(start).SetMaxResults(limit);

			total = Session.CreateQuery(@"select count(*) " + sqlStr)
				.SetString("query", query + "%")
				.SetString("DepCode", depCode)
				.SetEnum("PersonState", PersonState.Normal)
				.UniqueResult<long>();

			return q.List<object[]>();
		}

		public IList<HospUser> GetUserListByRoleAndDep(string query, string roleCode, string depCode, int start, int limit, string sort, string dir, List<DataFilter> filters, out long total)
		{
			// filter
			var strFilter = base.GetHqlstrByExtFilter(filters, "t");
			// 排序
			string ordStr = string.IsNullOrEmpty(sort) ? string.Empty : " order by t." + sort + " " + dir;
			// sql条件
			string sqlStr = @" from HospUser as t 
								left join t.Roles as r 
								left join t.Departments as d
								where t.State = :PersonState 
									and t.InputCode1 like (:query)
									and r.IsDelete = 0 and r.Code = :RoleCode
									and d.IsDelete = 0 and d.Code = :DepCode"
				+ (string.IsNullOrEmpty(strFilter) ? string.Empty : " and " + strFilter);
				
			var q = Session.CreateQuery(@"select t " + sqlStr + ordStr)
				.SetString("query", query + "%")
				.SetString("RoleCode", roleCode)
				.SetString("DepCode", depCode)
				.SetEnum("PersonState", PersonState.Normal);
			if(limit > 0)
				q.SetFirstResult(start).SetMaxResults(limit);

			total = Session.CreateQuery(@"select count(*) " + sqlStr)
				.SetString("query", query + "%")
				.SetString("RoleCode", roleCode)
				.SetString("DepCode", depCode)
				.SetEnum("PersonState", PersonState.Normal)
				.UniqueResult<long>(); ;

			return q.List<HospUser>();
		}

		public HospUser GetById(string id)
		{
			try
			{
				var query = Session.CreateQuery(@"select distinct u from HospUser as u
													left join fetch u.Departments
													left join fetch u.Roles
												   where u.Id=:Id");
				query.SetString("Id", id);

				IList<HospUser> result = query.List<HospUser>();

				if (result.Count <= 0)
					throw new RepositoryException("返回实体为空");
				else
					return result[0];
			}
			catch (Exception ex)
			{
				throw new RepositoryException("获取实体失败", ex);
			}
		}

		/// <summary>
		/// 查询用户信息和菜单
		/// </summary>
		/// <param name="id"></param>
		/// <returns></returns>
		public HospUser GetByIdWithMenu(string id)
		{
			try
			{
				var query = Session.CreateQuery(@"select distinct u from HospUser as u
													left join fetch u.MenuNodes
												   where u.Id=:Id");
				query.SetString("Id", id);

				IList<HospUser> result = query.List<HospUser>();

				if (result.Count <= 0)
					throw new RepositoryException("返回实体为空");
				else
					return result[0];
			}
			catch (Exception ex)
			{
				throw new RepositoryException("获取实体失败", ex);
			}
		}

		//验证用户名密码是否正确
		public bool Validate(string loginName, string pwd)
		{
			var query = Session.CreateQuery(@"select count(u) from HospUser as u 
				where u.LoginName=:LoginName and u.Pwd=:Pwd and u.State=:State")
				.SetString("LoginName", loginName)
				.SetString("Pwd", pwd)
				.SetEnum("State", PersonState.Normal)
				.UniqueResult<long>();
			return query == 1;
		}

		//验证用户Id密码是否正确
		public bool ValidateById(string userId, string pwd)
		{
			var query = Session.CreateQuery(@"select count(u) from HospUser as u 
				where u.Id=:UserId and u.Pwd=:Pwd and u.State=:State")
				.SetString("UserId", userId)
				.SetString("Pwd", pwd)
				.SetEnum("State", PersonState.Normal)
				.UniqueResult<long>();
			return query == 1;
		}

		//通过用户名密码获取用户信息
		public HospUser GetByName(string loginName)
		{
			var query = Session.CreateQuery(@"select u from HospUser as u where u.LoginName=:LoginName")
				.SetString("LoginName", loginName)
				.UniqueResult<HospUser>();
			return query;
		}
		#endregion
	}
}
